import 'package:fl_chart/fl_chart.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:sleep/db/merroy_db.dart';
import 'package:sleep/model/setting/setting.dart';
import 'package:sleep/provider/db_provider.dart';
import 'package:sleep/provider/wave_deatil_provider/sleep_detail_provider.dart';

enum Sleeptate {
  deepSleep,
  lightSleep,
  awake,
}

Map map = {
  Sleeptate.deepSleep: 3,
  Sleeptate.lightSleep: 2,
  Sleeptate.awake: 1,
};

extension MLState on Sleeptate {
  int toInt() {
    return map[this];
  }
}

class SleeptateModel {
  final Sleeptate state;
  final int time;

  SleeptateModel(this.state, this.time);
}

class SleeptateHelp {
  final SleepSetting setting;

  SleeptateHelp(this.setting);
  Sleeptate currentState(double rate) {
    if (isDeepSleep(rate)) return Sleeptate.deepSleep;
    if (isLightSleep(rate)) return Sleeptate.lightSleep;

    return Sleeptate.awake;
  }

  bool isLightSleep(double rate) {
    return rate < setting.shallow!;
  }

  bool isDeepSleep(double rate) {
    return rate < setting.deep!;
  }
}

class SleeptatePro {
  final Sleeptate state;
  final List<List<FlSpot>> sleeppot;

  SleeptatePro(this.state, this.sleeppot);
}

int before = 0;
SleeptatePro? fstate;
final sleeptateProvider = Provider<SleeptatePro?>((ref) {
  final sleep = ref.watch(sleepDetailProvider);

  final setting = ref
      .watch(dbProvider)
      .sleepSetting()
      .conbine(SleepSetting.defaultSetting());

  final current = DateTime.now().millisecondsSinceEpoch;
  if (MerroyDB.share().sleepStartTime == null) {
    MerroyDB.share().sleepStartTime = current; //设置初始值
  }
  final start = MerroyDB.share().sleepStartTime;
  //每一秒采集一次状态
  if (sleep.rr != '-') {
    final state = SleeptateHelp(setting).currentState(double.parse(sleep.rr));
    if (current - before > 1000) {
      before = current;
      MerroyDB.share().sleepStates.add(SleeptateModel(
            state,
            (current - start!) ~/ 1000,
          ));
    }

    List models = MerroyDB.share().sleepStates;
    List<FlSpot> spots = [];
    List<List<FlSpot>> fullSpots = [];
    SleeptateModel? lastModel;
    if (models.isNotEmpty) {
      SleeptateModel first = models.first;

      for (SleeptateModel model in models) {
        final spot = FlSpot(
            (model.time - first.time).toDouble(), model.state.index.toDouble());
        if (lastModel == null || lastModel.state == model.state) {
          spots.add(spot);
        } else {
          fullSpots.add(spots);
          spots = [];
        }
        lastModel = model;
      }
      if (spots.isNotEmpty) fullSpots.add(spots);
    }

    fstate = SleeptatePro(state, fullSpots);
  }

  return fstate;
});
